package com.app.couponsharelife.ui.adapter

import android.graphics.Paint
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.HtmlBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.databinding.GoodDetailDetailItemBinding
import com.app.couponsharelife.databinding.GoodDetailImageItemBinding
import com.app.couponsharelife.databinding.GoodDetailInfoItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by guluwa on 2018/11/24.
 */
class GoodDetailAdapter(private val list: MutableList<Any>,
                        private val activity: GoodDetailActivity?,
                        private val listener: OnClickListener) :
        androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {

    private var isShowGoodDetail = true
    private var isWeb=false
    private val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    private val df = DecimalFormat("#0.00")
    private var images = mutableListOf<String>()

    fun setData(data: List<Any>) {
        list.clear()
        list.addAll(data)
        for (item in data) {
            if (item is String){
                images.add(item)
            }
        }
        if (list.size>1){
            isWeb=true
        }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return when (viewType) {
            0 -> ViewHolderTip(DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.page_list_tip_item, parent, false))
            1 -> ViewHolder(DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.good_detail_info_item, parent, false))
            2 -> ViewHolderDetail(DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.good_detail_detail_item, parent, false))
            else -> ViewHolderImage(DataBindingUtil.inflate(
                    LayoutInflater.from(parent.context), R.layout.good_detail_image_item, parent, false))
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun getItemViewType(position: Int): Int {
        return when {
            list[position] is PageTipBean -> 0
            list[position] is TaobaoGoodBean -> 1
            list[position] is HtmlBean -> 2
            else -> 3
        }

    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        when {
            getItemViewType(position) == 0 -> (holder as ViewHolderTip).databinding.pageTipBean = list[position] as PageTipBean
            getItemViewType(position) == 1 -> {
                holder as ViewHolder
                val good = list[position] as TaobaoGoodBean
                val wenAn=good.goodsWenAn?:""
                if (wenAn.isNotEmpty()){
                    holder.databinding.goodsdetailLlWenAn.visibility=View.VISIBLE
                    holder.databinding.viewXian.visibility=View.VISIBLE
                    holder.databinding.goodsdetailTvGoodsWenAn.text=wenAn
                }else{
                    holder.databinding.goodsdetailLlWenAn.visibility=View.GONE
                    holder.databinding.viewXian.visibility=View.GONE
                }
                if (good.images.isNotEmpty()) {
                    holder.databinding.mBanner.start(good.images)
                } else {
                    if (good.pict_url is String)
                        holder.databinding.mBanner.start(arrayListOf(good.pict_url as String))
                }
                if (good.has_coupon){
                    holder.databinding.goodsdetailQuanprice.text=String.format("¥%s", good.coupon_price)
                    holder.databinding.goodsdetailLlq1.visibility=View.VISIBLE
                }else{
                    holder.databinding.goodsdetailLlq1.visibility=View.INVISIBLE
                }
                holder.databinding.goodsdetailJiangprice.text="￥${good.vip_commission}"
                activity?.registerLifeListener(holder.databinding.mBanner)
                holder.databinding.tvGoodName.text = "     "+good.title
                holder.databinding.imagGoodstype.setImageResource(good.userType)
                holder.databinding.tvOriginalPriceType.text=good.goodsSource+"价"
                holder.databinding.tvOriginalPrice.text = "￥${good.original_price}"//String.format("¥ %s", df.format(good.original_price.toDouble()))
                holder.databinding.tvOriginalPrice.paintFlags = holder.databinding.tvOriginalPrice.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                holder.databinding.tvCouponPrice.text = String.format("¥%s", df.format(good.final_price.toDouble()))
                holder.databinding.tvGoodVolume.text =good.volume.replace("月销","已售") //String.format("销量 %s", good.volume)
                if (good.has_coupon) {
                    holder.databinding.tvCouponPriceTitle.text = "券后"
                    holder.databinding.clGetCoupon.visibility = View.VISIBLE
                    holder.databinding.tvCouponInfo.text = good.coupon_price
                    holder.databinding.tvCouponRetainNum.text = String.format("使用期限：%s-%s", good.coupon_start_time,good.coupon_end_time)
                } else {
                    holder.databinding.tvCouponPriceTitle.text = "抢"
                    holder.databinding.clGetCoupon.visibility = View.GONE
                }
                if (good.shop_title.isNotEmpty()){
                    holder.databinding.goodsdetailClshop.visibility=View.VISIBLE
                    holder.databinding.goodsdetailTvshopname.text=good.shop_title
                    holder.databinding.goodsdetailTvshoptype
                            .setImageResource(when(good.goodsSource){
                                "淘宝"->{R.drawable.goodsdetail_tb}
                                "天猫"->{R.drawable.goodsdetail_tm}
                                "拼多多"->{R.drawable.goodsdetail_pdd}
                                else->{R.drawable.goodsdetail_tb}
                            })
                }else{
                    holder.databinding.goodsdetailClshop.visibility=View.GONE
                }
                holder.databinding.ivGoodDetailOpen.setImageResource(if (!isShowGoodDetail) R.drawable.ic_problem_arrow_close else R.drawable.ic_problem_arrow_open)
            }
            getItemViewType(position) == 2 -> {
                if ((list[position] as HtmlBean).html != "") {
                    (holder as ViewHolderDetail).databinding.mWebView.loadDataWithBaseURL(null, String.format("%s <div> %s </div>", "<style type=\"text/css\">\n" +
                            "\t\timg{ margin:0; padding:0;width:100%;} " +
                            "\t</style>", (list[position] as HtmlBean).html), "text/html", "utf-8", null)
                }
                if (isShowGoodDetail) {
                    (holder as ViewHolderDetail).databinding.mWebView.visibility = View.VISIBLE
                } else {
                    (holder as ViewHolderDetail).databinding.mWebView.visibility = View.GONE
                }
            }
            else -> {
                /*Glide.with(holder.itemView).load(list[position])
                        .downloadOnly(object : SimpleTarget<File>() {
                            override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                                // 将保存的图片地址给SubsamplingScaleImageView,这里注意设置ImageViewState设置初始显示比例
                                val bitmap = BitmapFactory.decodeFile(resource.absolutePath, AppUtils.getBitmapOption(1))
                                // 显示处理好的Bitmap图片
                                (holder as ViewHolderImage).databinding.ivGoodImage.setImageBitmap(bitmap)
                            }
                        })*/
                Glide.with(holder.itemView.context).asBitmap()
                        .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                        .load(list[position])
                        .into((holder as ViewHolderImage).databinding.ivGoodImage)
            }
        }
    }

    inner class ViewHolder(val databinding: GoodDetailInfoItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.root.setOnClickListener {
                if (adapterPosition != -1) {
                    listener.click(0, list[adapterPosition])
                }
            }
            databinding.clGoodDetail.setOnClickListener {
                isShowGoodDetail = !isShowGoodDetail
                if (images.isNotEmpty()) {
                    if (isShowGoodDetail) {
                        if (isWeb){
                            list.addAll(2, images)
                        }else{
                            list.addAll(1, images)
                        }
                    } else {
                        if (isWeb){
                            list.subList(2, list.size).clear()
                        }else{
                            list.subList(1, list.size).clear()
                        }
                    }
                }
                notifyDataSetChanged()
            }
            databinding.clGetCoupon.setOnClickListener {
                listener.click(0, "GetCoupon")
            }
            databinding.tvGoodName.setOnLongClickListener {
                listener.click(100, databinding.tvGoodName.text?:"")
                return@setOnLongClickListener true
            }
        }
    }

    inner class ViewHolderDetail(val databinding: GoodDetailDetailItemBinding) : RecyclerView.ViewHolder(databinding.root)

    inner class ViewHolderImage(val databinding: GoodDetailImageItemBinding) : RecyclerView.ViewHolder(databinding.root)
}